var express = require('express');
var router = express.Router();
const { DataModel, cateModel } = require("../model/model");
const mongoose = require('mongoose');  // 导入 mongoose

const multiparty = require("multiparty");

// 上传的路由，处理单个文件上传（也可以处理分块上传）
router.post('/uploads', (req, res) => {
  const form = new multiparty.Form();
  form.uploadDir = 'uploads';
  form.parse(req, (err, a, imgData) => {
    if (err) {
      return res.status(500).send({ code: 500, message: 'File upload failed' });
    }
    console.log(imgData);
    res.send({
      code: 200,
      path: 'http://127.0.0.1:3000/' + imgData.file[0].path
    });
  });
});

router.get('/cate', async (req, res) => {
  try {
    let cate = await cateModel.find();
    res.send({
      code: 200, cate
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      code: 500,
      message: 'Failed to retrieve categories'
    });
  }
});

router.post('/add', async (req, res) => {
  try {
    console.log(req.body);
    await DataModel.create(req.body);
    res.send({
      code: 200,
      message: 'Data added successfully'
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      code: 500,
      message: 'Failed to add data'
    });
  }
});

router.get('/list', async (req, res) => {
  try {
    let {cate,page,pageSize,content} = req.query 

    let arr = []

    let contentReg = new RegExp(content)
    if(content) arr.push({
        content:contentReg
    })

    if(cate) arr.push({
        cate
    })
    let list = await DataModel.find({ $and : arr  });
    list = await DataModel.find({ $and : arr  }).skip((page-1)*pageSize).limit(pageSize)
    let total = await DataModel.find({ $and : arr  }).countDocuments()
    res.send({
      code: 200, list,total
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      code: 500,
      message: 'Failed to retrieve list'
    });
  }
});



//修改
router.post('/upd', async (req, res) => {
  let body = req.body
  let id = body._id
  console.log(body);

  let list = await DataModel.updateOne({ _id: id }, body)
  res.send({
    code: 200, list
  })
})

//回显
router.get('/edit', async (req, res) => {
  let { id } = req.query
  let list = await DataModel.find({ _id: id })
  res.send({
    code: 200, list
  })
})

//批量删除
router.post('/deleAll', async (req, res) => {
  let ids = req.body
  console.log(ids);

  await DataModel.deleteMany({ _id: ids })
  res.send({
    code: 200
  })
})

router.delete('/del',async(req,res)=>{
    let _id = req.query
    await DataModel.deleteOne({_id:_id})
    res.send({
        code:200
    })
})

module.exports = router;
